package api

import (
	"context"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetApiByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetApiByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetApiByIdLogic {
	return &GetApiByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetApiByIdLogic) GetApiById(in *backend.IDReq) (*backend.ApiInfo, error) {
	if in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	res, err := l.svcCtx.SysApi.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &backend.ApiInfo{
		Id:          pointy.GetPointer(res.ID),
		Path:        pointy.GetPointer(res.Path),
		Description: pointy.GetPointer(res.Description),
		Group:       pointy.GetPointer(res.APIGroup),
		Method:      pointy.GetPointer(res.Method),
		Required:    pointy.GetPointer(uint32(res.IsRequired)),
		Status:      pointy.GetPointer(uint32(res.Status)),
		CreatedAt:   pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt:   pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
		DeletedAt:   pointy.GetPointer(modelx.FormatNullDotTime(res.DeletedAt, "")),
	}, nil
}
